package com.chuanqi.shop.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chuanqi.shop.domain.CustomerRegister;
import com.chuanqi.shop.service.CustomerRegisterService;

@Controller
@RequestMapping("/customer")
public class CustomerRegisterController {
	@Autowired
    private CustomerRegisterService customerLoginService;
	
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String createGet(Model model) {    	
		CustomerRegister login = new CustomerRegister();    	
        model.addAttribute("login", login);            	
        
        return "shop/register/form";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String create(@Valid @ModelAttribute("login") CustomerRegister login, BindingResult bindingResult, Model model) {
    	if (bindingResult.hasErrors()) {   		     	
        	return "shop/register/form";
        }
    	
    	customerLoginService.createCustomerRegister(login);
        return "redirect:/customer/registerSuccess";    	       
    }
    
    @RequestMapping(value = "/registerSuccess", method = RequestMethod.GET)
    public String registerSuccessGet(Model model) {    	
        return "shop/register/registerSuccess";
    }
    
    @RequestMapping(value = "/checkTelephone", method = RequestMethod.GET)
	@ResponseBody
	public String checkLoginName(@RequestParam("telephone") String telephone) {
		if(customerLoginService.getByTelephone(telephone)!=null){
			return "false";
    	}else {
    		return "true";
		}		 
	}
	
	@RequestMapping(value = "/checkTelephoneById/{id}", method = RequestMethod.GET)
	@ResponseBody
	public String checkLoginNameById(@PathVariable("id") Long id, @RequestParam("telephone") String telephone) {
		if(customerLoginService.getByTelephone(telephone)!=null && ! telephone.equals(customerLoginService.getById(id).getTelephone())){
			return "false";
    	}else {
    		return "true";
		}		 
	}
	
    
}
